import React from 'react';
import { ScrollView, View, RefreshControl } from 'react-native';
import { Dialog } from './Dialog';

const c_t1st = -1, c_t0 = 0, c_t1 = 1;
// 自定义ScrollView列表 附带下拉刷新功能 限制5秒钟只能刷新一次
export class Rlist extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            freshing : false,
        }
        this.timeout = c_t1st;
        this.freshed = this.freshed.bind(this);
    }

    componentWillMount(){
        this.onFresh(true);
    }
    onFresh(didMount){
        let  { freshing } = this.state;
        if(freshing){
            return;
        }
        const {onFresh} = this.props;
        if(onFresh){
            if(this.timeout == c_t1){
                Dialog.toast("操作频繁")
                return;
            }
            freshing = true;
            this.setState({ freshing });
            onFresh(didMount, this.freshed);
            if(this.timeout === c_t1st){
                this.timeout = c_t0;
            }else{
                this.timeout = c_t1;
                setTimeout(()=>this.timeout=c_t0, 5000);
            }
        }
    }
    freshed(){
        this.setState({
            freshing : false,
        });
    }
    render() {
        const {style, onFresh, children, ...other } = this.props
        return <ScrollView
            {...other}
            refreshControl={<RefreshControl
                //Android下只有一个 colors 是转圈的颜色
                colors={['#d11', '#000']}
                //ios 下 可以设置标题，转圈颜色，标题颜色
                title={'Loading...'}
                tintColor={'#d11'}
                titleColor={'#d11'}
                //刷新状态 false:隐藏，true:显示
                refreshing={this.state.freshing}
                //刷新触发的后执行的方法
                onRefresh={()=>this.onFresh(false)}
            />}
        >
            <View style={style}>{children}</View>
        </ScrollView>
    }
}
